import { PlusOutlined } from '@ant-design/icons';
import { Button, Divider, message, Input, Drawer, Image, Popconfirm, Select } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import UploadImg from '@/components/UploadImg';
import FormItem from 'antd/lib/form/FormItem';
import { queryRule, updateRule, addRule, removeRule } from './service';
import { handleReturnArray } from '@/utils/utils';
/**
 * 添加节点
 * @param fields
 */

const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');

  try {
    await addRule({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 * @param fields
 */

const handleUpdate = async (payload, actionRef) => {
  const hide = message.loading('正在修改');

  try {
    await updateRule(payload);
    hide();
    message.success('修改成功');
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};
/**
 *  删除节点
 * @param selectedRows
 */

const handleRemove = async (payload, actionRef) => {
  const hide = message.loading('正在删除');

  try {
    await removeRule(payload);
    hide();
    message.success('删除成功，即将刷新');
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [createEditModalVisible, handleEditModalVisible] = useState(false);
  const [count, setCount] = useState({});
  const [formValue, setFormValue] = useState(null);
  const [facePicture, setFacePicture] = useState(null);
  const actionRef = useRef();
  const handleSetFacePicture = (payload) => {
    setFacePicture(payload);
  };
  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      valueType: 'text',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '硬件名称',
      dataIndex: 'name',
      valueType: 'text',
    },
    {
      title: '硬件数量',
      dataIndex: 'count',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '硬件型号',
      dataIndex: 'sn',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '硬件规格',
      dataIndex: 'spec',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '硬件单价',
      dataIndex: 'unitPrice',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '硬件照片',
      dataIndex: 'url',
      valueType: 'text',
      width: 200,
      hideInSearch: true,
      render: (_, payload) => {
        return (
          <>
            {' '}
            <Image
              style={{ maxHeight: '50px' }}
              src={`${window.location.protocol}//${window.location.hostname}:81/file/` + _}
            />{' '}
          </>
        );
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <>
            {formValue ? (
              <FormItem name="facePicture">
                <UploadImg
                  subpath="hardWare"
                  showImgUrl={
                    `${window.location.protocol}//${window.location.hostname}:81/file/hardWare/` +
                    facePicture
                  }
                  imgUrl={facePicture}
                  handleSetFacePicture={handleSetFacePicture}
                />
              </FormItem>
            ) : (
              <FormItem name="facePicture">
                <UploadImg subpath="hardWare" handleSetFacePicture={handleSetFacePicture} />
              </FormItem>
            )}
          </>
        );
      },
    },
    {
      title: '是否中间件支撑',
      dataIndex: 'support',
      valueEnum: {
        0: {
          text: '否',
          status: 'Error',
          value: 0,
        },
        1: {
          text: '是',
          status: 'Success',
          value: 1,
        },
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <FormItem name="support" label={false}>
            <Select placeholder="请选择">
              {handleReturnArray(item.valueEnum, 2).map((item_in, index) => {
                if (item_in) {
                  return (
                    <Option key={index} value={item_in.value}>
                      {item_in.text}
                    </Option>
                  );
                }
              })}
            </Select>
          </FormItem>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleEditModalVisible(true);
              setFacePicture(record.url);
              setFormValue(record);
            }}
          >
            修改
          </a>
          <Divider type="vertical" />
          <Popconfirm
            placement="top"
            title="确定要删除吗?"
            onConfirm={() => {
              handleRemove(record.id, actionRef);
            }}
            okText="Yes"
            cancelText="No"
          >
            <a>删除</a>
          </Popconfirm>
        </>
      ),
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="硬件列表"
        actionRef={actionRef}
        bordered
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            onClick={() => {
              setFacePicture(null);
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 添加硬件
          </Button>,
        ]}
        request={(params, sorter, filter) => queryRule({ ...params, sorter, filter })}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: false,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        postData={(params) => {
          const { list, total } = params;
          setCount(total);
          return list;
        }}
        columns={columns}
        rowSelection={false}
      />
      <CreateForm
        title="添加硬件"
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
      >
        <ProTable
          onSubmit={async (value) => {
            if (facePicture !== null) {
              value.url = facePicture;
            }
            const success = await handleAdd(value);

            if (success) {
              handleModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          bordered
          type="form"
          columns={columns}
        />
      </CreateForm>
      <CreateForm
        title="修改硬件"
        onCancel={() => handleEditModalVisible(false)}
        modalVisible={createEditModalVisible}
      >
        <ProTable
          onSubmit={async (value) => {
            value.version = formValue.version + 1;
            value.id = formValue.id;
            if (facePicture !== null) {
              value.url = facePicture;
            }
            const success = await handleUpdate(value, actionRef);

            if (success) {
              handleEditModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          form={{ initialValues: formValue }}
          rowKey="id"
          bordered
          type="form"
          columns={columns}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
